import { extendClass } from "../../utils/index"
import { screenWidth, screenHeight } from '../../constant/index'
import Base from './base'
import { getCanvas } from '../../../ctx'
/**
 * 游戏基础的精灵类
 */
export default class Sprite extends Base {
  /**
   * 图片资源
   */
  image = null
  /**
   * 组件宽度
   */
  width = 0
  /**
   * 组件高度
   */
  height = 0
  /**
   * 组件坐标 - x
   */
  x = 0
  /**
   * 组件坐标 - y
   */
  y = 0
  /**
   * 子节点
   */
  constructor(imgSrc = '', width = 0, height = 0, x = 0, y = 0) {
    super()
    this.img = getCanvas().createImage()
    if (typeof imgSrc === 'string') {
      this.img.src = imgSrc
    }
    this.width = width
    this.height = height

    this.top = 0
    this.left = 0
    /**
     * 旋转角度
     */
    this.rotate = 0
    this.x = x
    this.y = y
    this.visible = true
    this.renderingCount = 0
    this.zIndex = 0
    this.parnet = null
    extendClass(this)
  }
  created() {

  }
  /**
   * 设置定位
   */
  setPosition(param) {
    const { x, y } = param
    this.x = x
    this.y = y
  }
  /**
   * 超出屏幕边界判断
   * param: {w: 0} w: 扩展宽度
   * @returns {boolean}
   */
  isFallscreen (w = 0) {
    if (this.y + w > screenHeight) {
      return true
    } else if (this.y - w < 0) {
      return true
    } else if (this.x - w > screenWidth) {
      return true
    } else if (this.x + w + this.width < 0) {
      return true
    }
    return false
  }
  /**
   * 擦边物体之前碰撞检测
   */
  collisionDetection (substance) {
    if (this.x < substance.x + substance.width &&
      this.x + this.width > substance.x &&
      this.y < substance.y + substance.height &&
      this.y + this.height > substance.y) {
      return true
    }
    return false
  }
  /**
   * 碰到地面
   */
  isCollideWithGround (h = 0) {
    return this.y + this.height >= screenHeight - h
  }
  /**
   * 更新坐标
   */
  update() {
    
  }
  /**
   * 将精灵图绘制在canvas上
   */
  render(ctx) {
    if (!ctx) return

    ctx.drawImage(
      this.img,
      this.x,
      this.y,
      this.width,
      this.height
    )
  }

  /**
   * 中心点碰撞检测
   */
  isCollideWith(sp) {
    const spX = sp.x + sp.width / 2
    const spY = sp.y + sp.height / 2

    if (!this.visible || !sp.visible) return false

    return !!(spX >= this.x + this.width / 3
              && spX <= this.x + this.width - this.width / 3
              && spY >= this.y
              && spY <= this.y + this.height)
  }
  /**
   * 墙面碰撞检测 左右两边
   */
  isCollideWithWallLeftAndRight(offset = 0) {
    return this.x + offset <= 0 || this.x + this.width - offset >= screenWidth
  }
  /**
 * 墙面碰撞检测 左边
 */
  isCollideWithWallLeft(offset = 0) {
    return this.x + offset <= 0
  }
  /**
 * 墙面碰撞检测 右边
 */
  isCollideWithWallRight(offset = 0) {
    return this.x + this.width - offset >= screenWidth
  }
}
